<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:27
 */

namespace app\firm\controller;

use think\Controller;
use think\Config;
use redis\Redis;
use think\Request;
use think\Session;
use app\firm\model\ProjectUser;
use app\firm\model\ProjectBank;
use app\firm\validate\bankValidate;
use app\Tools\VerifyCodeImage;
use expand\Yunst;
use expand\YunPay;

class Login extends Controller
{
    
    /**
     * 登录
     * @param Request $request
     * @param \app\firm\model\ProjectUser $projectUser
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author cpy(1442435897@qq.com)
     */
    public function login(Request $request, ProjectUser $projectUser) {
        $param = $request->param();
        $redis = Redis::instance();
        if (Session::has('code')) {
            $code = Session::get('code');
            if (strtolower($code) === strtolower(trim($param['code']))) {
                if ($param['mobile'] && $param['password']) {
                    $where['mobile'] = ['eq', $param['mobile']];
                    $user_info = $projectUser->getUserInfo($where);
                    if ($user_info) {
                        $password = sha1(md5($param['password'] . $user_info['salt']));
                        if ($password == $user_info['password']) {
                            $token = accessToken();
                            if (!empty($user_info['token']))
                                $redis->hDel('firm_info', $user_info['token']);
                            $user_info['login_time'] = time();
                            $user_info['login_ip'] = $_SERVER['HTTP_X_FORWARDER_FOR'];
                            $redis->hSet('firm_info', $token, json_encode($user_info));
                            $redis->set('user:' . $user_info['id'], $token);
                            $redis->expire('user:' . $user_info['id'],7200);
                            Session('user_id' , $user_info['id']);
                            $data['token'] = $token;
                            if ($projectUser->save(['token' => $token], ['mobile' => $param['mobile']])) {
                                $result = Config::get('code.success');
                                $result['token'] = $token;
                                $res['mobile'] = $user_info['mobile'];
                                $res['company_name'] = $user_info['company_name'];
                                $res['status'] = $user_info['status'];
                                $res['safemobile'] = $user_info['safemobile'];
                                $result['data'] = $res;
                                session::delete('code');
                            } else {
                                $result = Config::get('code.error');
                            }
                        } else {
                            $result['msg'] = '密码错误';
                            $result['status'] = 201;
                        }
                    } else {
                        $result['msg'] = '该手机号未注册';
                        $result['status'] = 201;
                    }
                } else {
                    $result = Config::set('code.mistake');
                }
            } else {
                $result = Config::get('code.codeFail');
            }
        } else {
            $result = Config::get('code.codeEmpty');
        }
        return json($result);
    }

    /*
     * 获取图形验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function getPicCode(Request $request)
    {
        $code = createRandomNum(4);
        Session('code',$code);
        $imageCode = new VerifyCodeImage(80,20,$code);
        $file = $imageCode->show();
        $result = Config::get('code.success');
        $result['code'] = $file;
        return json($result);
    }
    
    /*
     * 发送验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function SendYsCode(Request $request) {
        $param = $request->param();
        $user_info = $request->firm_info;
        $YunClass = new Yunst();
        $mobile2 = $param['mobile'];
        /* if($mobile2){
          $uid = $this->cModel->where(['yunmobile'=>$mobile2])->value('id');
          if($uid > 0){
          return ajaxReturn('该手机已存在');
          }
          $mobile = $mobile2;
          } */
        if (empty($mobile2)) {
            $result = Config::get('code.null');
        }
        $res = $YunClass->sendVerifCode($user_info['bizUserId'], $mobile2);
        if ($res['status'] == 'OK') {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
            $result['msg'] = $res['message'];
        }
        return json($result);
    }

    /*
     * 认证手机号
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function bindMobile(Request $request , ProjectUser $projectUser) {
        $param = $request->param();
        $redis = Redis::instance();
        $user_info = $request->firm_info;
        $YunClass = new Yunst();
        $mobile = $param['mobile'];
        $code = $param['code'];
        $res = $YunClass->bindMobile($user_info['bizUserId'], $mobile, $code);
        file_put_contents(date("Y-m-d H", time()) . 'bindMobile.txt', json_encode($res) . PHP_EOL, FILE_APPEND);
        if ($res['status'] == 'OK') {
            $projectUser->where(['id' => $user_info['id']])->update(['safemobile' => 'YES', 'yunmobile' => $mobile]);
            $token = $redis->get('user:' . $user_info['id']);
            $user_info['safemobile'] = 'YES';
            $redis->hSet('firm_info' , $token , json_encode($user_info));
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
            $result['msg'] = $res['message'];
        }
        return json($result);
    }

    public function logout(Request $request){
        $redis = Redis::instance();
        $user_info = $request->firm_info;
        $redis->hDel('firm_info', $user_info['token']);
        $result = Config::get('code.success');
        $result['msg'] = '退出成功';
        return json($result);
    }
    
    public function test() {
        return $this->fetch();
    }

}